package com.demo.personalaccountingbackend.controller;

import com.demo.personalaccountingbackend.data.Result;
import com.demo.personalaccountingbackend.dto.*;
import com.demo.personalaccountingbackend.entity.User;
import com.demo.personalaccountingbackend.service.TokenService;
import com.demo.personalaccountingbackend.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import lombok.RequiredArgsConstructor;

import java.time.LocalDateTime;

/**
 * 类描述信息
 *
 * @author zgx
 * @version 1.0
 * @date 2025/10/14$ 10:34$
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;

    private final TokenService tokenService;
    @PostMapping("/login")
    public Result<TokenDTO> login(@Validated @RequestBody LoginDTO loginDTO) {
        try {
            // 查询用户
            User user = userService.findByUsername(loginDTO.getUsername());
            if (user == null) {
                return Result.failed("用户名或密码错误");
            }

            // 检查用户状态
            if (user.getStatus() == 1) {
                return Result.failed("账户已被禁用");
            }

            // 验证密码
            if (!userService.checkPassword(loginDTO.getPassword(), user.getPassword())) {
                return Result.failed("用户名或密码错误");
            }

            // 更新最后登录时间
            user.setLastLoginTime(LocalDateTime.now());
            userService.updateById(user);

            // 生成令牌
            TokenDTO tokenDTO = tokenService.createToken(user.getId(), user.getUsername());

            log.info("用户 {} 登录成功", loginDTO.getUsername());
            return Result.success(tokenDTO);

        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage(), e);
            return Result.failed("登录失败");
        }
    }

    @PostMapping("/refresh")
    public Result<TokenDTO> refreshToken(@Validated @RequestBody RefreshTokenDTO refreshTokenDTO) {
        try {
            String newAccessToken = tokenService.refreshAccessToken(refreshTokenDTO.getRefreshToken());

            TokenDTO tokenDTO = new TokenDTO(newAccessToken, refreshTokenDTO.getRefreshToken(),
                    tokenService.getExpirationTime(), tokenService.getRefreshExpirationTime());

            return Result.success(tokenDTO);

        } catch (Exception e) {
            log.error("刷新令牌失败: {}", e.getMessage());
            return Result.failed("刷新令牌失败");
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public LoginResponse register(@Valid @RequestBody User user) {
        return userService.register(user);
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    public ApiResponse checkUsername(@RequestParam String username) {
        boolean exists = userService.existsByUsername(username);
        if (exists) {
            return ApiResponse.error("用户名已存在");
        }
        return ApiResponse.success("用户名可用");
    }

    @GetMapping("/health")
    public String health() {
        return "Service is running successfully!";
    }

    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token != null) {
                tokenService.invalidateToken(token);
            }
            return Result.success();
        } catch (Exception e) {
            log.error("退出登录失败: {}", e.getMessage());
            return Result.failed("退出登录失败");
        }
    }

    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}